package org.sample.thread;

/** 线程互斥 */
public class ThreadMutex2 {

    public static void main(String[] args) {
        final Business2 b = new Business2();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                b.main(5);
            }
        }).start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                b.sub(2);
            }
        }).start();
    }
}

class Business2 {

    private boolean bool = true;

    public synchronized void main(int count) {
        while (!bool) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        int i = 0;
        while (i++ < count) {
            System.out.println("主线程-" + i);
        }
        System.out.println();
        bool = false;
        this.notify();
    }

    public synchronized void sub(int count) {
        while (bool) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        int i = 0;
        while (i++ < count) {
            System.out.println("子线程-" + i);
        }
        System.out.println();
        bool = true;
        this.notify();
    }
}